package blue.datacenter;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class MachineConn implements ConnectionInterface {
	// TODO
	private SocketChannel sock_channel_;
	private int id_;
	private String ip_;
	private int port_;
	private ConnectionType type_;
	private String last_command_;  // Used to saved the last command.
	private Object attach_obj_;
	
	MachineConn(String ip, int port) throws IOException{
		// TODO create connections
		ip_ = ip;
		port_ = port;
		type_ = ConnectionType.MachineConn;
		ByteBuffer.allocate(512);
		last_command_ = null;
		
		System.out.println("Machine Connect to "+ip_+":"+port_);
		sock_channel_ = SocketChannel.open();
		sock_channel_.connect(new InetSocketAddress(ip_, port_));
	}

	@Override
	public SocketChannel getSockChannel() {
		return sock_channel_;
	}

	@Override
	public String getIP() {
		return ip_;
	}

	@Override
	public int getPort() {
		return port_;
	}

	@Override
	public String getSN() {
		return ip_+":"+port_;
	}

	@Override
	public String read() throws IOException {
		String recv_str = null;
		try {
			ByteBuffer recv_buf = ByteBuffer.allocate(256);
			//recv_buf.clear();
			int recv_cnt = sock_channel_.read(recv_buf);
			recv_buf.flip();
			byte[] recv_bytes=new byte[recv_cnt];
			recv_buf.get(recv_bytes, 0, recv_cnt);
			recv_str = new String(recv_bytes,Charset.forName("UTF-8"));
			// recv success , it's meanings the last command is success, we need to clear last_command_.
			last_command_ = null;
		}catch(IOException e) { }
	    
		return recv_str;
	}

	@Override
	public int write(String msg) throws IOException {
	    byte[] bytes = msg.getBytes( Charset.forName("UTF-8" ));
		ByteBuffer send_buf = ByteBuffer.allocate(256);
		//send_buf.clear();
		send_buf.put(bytes);
		send_buf.flip();
		last_command_ = msg;
		//sock_channel_.
		return sock_channel_.write(send_buf);
	}

	@Override
	public ConnectionType getType() {
		return type_;
	}

	@Override
	public void setTypePrivilege() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean reconnection() throws IOException {
		System.out.println("Re-connect to Machine "+ip_+":"+port_);
		sock_channel_ = SocketChannel.open();
		sock_channel_.connect(new InetSocketAddress(ip_, port_));

		// Resend the last command.
		if (last_command_!=null) {
			write(last_command_);
		}
		
		return true;
	}

	@Override
	public int getId() {
		return id_;
	}

	@Override
	public void setId(int id) {
		id_ = id;
	}
	
	@Override
	public void setAttach(Object obj){ attach_obj_ = obj; }

	@Override
	public Object getAttach(){ return attach_obj_;}
}
